package com.reader;

import java.io.File;
import java.util.Hashtable;
import java.util.Map;

import com.iface.ILogProcessor;
import com.iface.ILogReader;

public class LogReader implements ILogReader {

	final static String LogFileExtension = ".log";// TODO read this from config.

	Map<String, FileHandler> logFileMap;

	String directoryPath = "D:/data"; //TODO read this from config.

	private ILogProcessor logProcessor;

	@Override
	public void readLog(ILogProcessor logProcessor) {
		this.logProcessor = logProcessor;
		start();
	}

	private void start() {
		File[] files = getLogFiles(directoryPath);
		logFileMap = getMapOfLogFiles(files);
		DirectoryWatchService directoryWatchService = new DirectoryWatchService();
		directoryWatchService.setLogReader(this);
		directoryWatchService.getEvents(directoryPath);
	}

	/**
	 * To get List of log files
	 * 
	 * @param directoryPath
	 * @return File[]
	 */
	private File[] getLogFiles(String directoryPath) {
		File dir = new File(directoryPath);
		return dir.listFiles(new LogFilenameFilter());
	}

	private Map<String, FileHandler> getMapOfLogFiles(File[] files) {
		Hashtable<String, FileHandler> map = new Hashtable<String, FileHandler>(
				files.length);
		for (File file : files) {
			map.put(file.getName(), new FileHandler(file));
		}
		return map;

	}

	public void updated(String fileName) {
		FileHandler fileHandler = logFileMap.get(fileName);
		if (fileHandler != null) {
			String logChunk = fileHandler.readLog();
			logProcessor.processLog(logChunk);
		}

	}

}
